using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using OrderingSystem.Core.Interfaces;
using System.IO;

namespace OrderingSystem.Infrastructure.Services
{
    public class FileService : IFileService
    {
        private readonly string _baseUploadPath;
        private readonly string[] _allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif" };
        private readonly long _maxFileSize = 5 * 1024 * 1024; // 5MB

        public FileService(IConfiguration configuration)
        {
            // 获取当前目录并输出
            var currentDirectory = Directory.GetCurrentDirectory();
            Console.WriteLine($"当前工作目录: {currentDirectory}");
            
            // 设置基础上传路径
            _baseUploadPath = Path.Combine(currentDirectory, "wwwroot");
            Console.WriteLine($"基础上传路径: {_baseUploadPath}");
            
            // 确保 wwwroot 目录存在
            if (!Directory.Exists(_baseUploadPath))
            {
                Console.WriteLine($"创建 wwwroot 目录: {_baseUploadPath}");
                Directory.CreateDirectory(_baseUploadPath);
            }
            else
            {
                Console.WriteLine($"wwwroot 目录已存在: {_baseUploadPath}");
            }
            
            // 确保 upload 目录存在
            var uploadDir = Path.Combine(_baseUploadPath, "upload");
            Console.WriteLine($"上传目录路径: {uploadDir}");
            
            if (!Directory.Exists(uploadDir))
            {
                Console.WriteLine($"创建 upload 目录: {uploadDir}");
                Directory.CreateDirectory(uploadDir);
            }
            else
            {
                Console.WriteLine($"upload 目录已存在: {uploadDir}");
            }
        }

        public async Task<string> UploadFileAsync(IFormFile file, string subDirectory = "")
        {
            Console.WriteLine($"开始上传文件: {file.FileName}, 大小: {file.Length} 字节, 子目录: {subDirectory}");
            
            if (file == null || file.Length == 0)
            {
                throw new ArgumentException("未选择文件");
            }

            if (file.Length > _maxFileSize)
            {
                throw new ArgumentException("文件大小超过限制");
            }

            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            Console.WriteLine($"文件扩展名: {extension}");
            
            if (!_allowedExtensions.Contains(extension))
            {
                throw new ArgumentException("不支持的文件类型");
            }

            var relativePath = "upload";
            var uploadPath = Path.Combine(_baseUploadPath, relativePath);
            Console.WriteLine($"初始上传路径: {uploadPath}");

            if (!string.IsNullOrEmpty(subDirectory))
            {
                Console.WriteLine($"处理子目录: {subDirectory}");
                
                switch (subDirectory.ToLower())
                {
                    case "dish":
                        relativePath = "upload/dishes";
                        break;
                    case "news":
                        relativePath = "upload/news";
                        break;
                    case "avatar":
                        relativePath = "upload/avatar";
                        break;
                    default:
                        relativePath = Path.Combine("upload", subDirectory).Replace("\\", "/");
                        break;
                }
                
                uploadPath = Path.Combine(_baseUploadPath, relativePath.Replace("/", Path.DirectorySeparatorChar.ToString()));
                Console.WriteLine($"最终上传路径: {uploadPath}");
                
                if (!Directory.Exists(uploadPath))
                {
                    Console.WriteLine($"创建目录: {uploadPath}");
                    Directory.CreateDirectory(uploadPath);
                }
                else
                {
                    Console.WriteLine($"目录已存在: {uploadPath}");
                }
            }

            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var random = new Random().Next(1000, 9999);
            var fileName = $"{timestamp}_{random}{extension}";
            var filePath = Path.Combine(uploadPath, fileName);

            Console.WriteLine($"准备保存文件到: {filePath}");
            
            try
            {
                // 确保目录存在
                var directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Console.WriteLine($"创建目录: {directoryName}");
                    Directory.CreateDirectory(directoryName);
                }
                
                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                
                Console.WriteLine($"文件保存成功: {filePath}");
                
                // 验证文件是否存在
                if (File.Exists(filePath))
                {
                    Console.WriteLine($"文件存在确认: {filePath}");
                }
                else
                {
                    Console.WriteLine($"警告: 文件保存后不存在: {filePath}");
                }
                
                var returnPath = relativePath + "/" + fileName;
                Console.WriteLine($"返回路径: {returnPath}");
                return returnPath;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存文件时出错: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");
                throw;
            }
        }

        public Task<bool> DeleteFileAsync(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                Console.WriteLine("删除文件: 路径为空");
                return Task.FromResult(false);
            }

            var fullPath = Path.Combine(_baseUploadPath, filePath.TrimStart('/'));
            Console.WriteLine($"尝试删除文件: {fullPath}");

            if (!File.Exists(fullPath))
            {
                Console.WriteLine($"文件不存在: {fullPath}");
                return Task.FromResult(false);
            }

            try
            {
                File.Delete(fullPath);
                Console.WriteLine($"文件删除成功: {fullPath}");
                return Task.FromResult(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除文件时出错: {ex.Message}");
                return Task.FromResult(false);
            }
        }
    }
} 